package com.ys.controller.web.storage;

import com.ys.config.MenuId;
import com.ys.dto.SubGridConfigDto;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.storage.*;
import com.ys.entity.sys.YsMenu;
import com.ys.enume.storage.TccFbaBoxUpEnum;
import com.ys.enume.storage.TccFbaBoxUpItemEnum;
import com.ys.enume.storage.TccFbaDoCancelEnum;
import com.ys.enume.storage.TccFbaPlanEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.vo.Flow;
import com.ys.vo.W;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * FBA取消单
 */
@Controller
@RequestMapping("/web/storage/tccFbaCancel")
public class WebTccFbaCancelController {
	private static final Logger logger = LoggerFactory.getLogger(WebTccFbaCancelController.class);

	@Autowired
	private CommonApiService<YsMenu> commonApiService;

	private final Long menuId_doCancel = MenuId.TCC_FbaCancel_DoCancel;

	private final Long menuId_BoxUpdoCancel = MenuId.TCC_FbaBoxUpDoCancel;
	@Autowired
	private CheckUtil checkUtil;

	/**
	 * 计划取消弹框
	 * @param bid 对应单号
	 * @param formType 表单类型
	 */
	@GetMapping("/doCancel")
	public String doCancel(Model model, HttpServletRequest request, HttpServletResponse response, String bid,int formType) {
		try {

			Map<String, Object> extraParam = new HashMap<>();
			int isOriginallyChw = 0;//是否原货位 0否1是
			String vck = "";//仓库
			String vkq = "";//库区
			String vhw = "";//货位
			String chw = "";//货位编码
			BigDecimal skuAmount = BigDecimal.ZERO;//按SKU计费标准
			BigDecimal boxAmount = BigDecimal.ZERO;//按箱计费标准
			BigDecimal unifiedAmount = BigDecimal.ZERO;//整单计费
			String amountExplain = "";//计费说明
			String bidFbaPlan = "";//FBA计划单号

			SubGridConfigDto subGridConfig=null;

			//TODO 计划单取消
			if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaPlan.value){

			}
			// 发货单取消
			else if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliver.value || formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliverWc.value){
				List<TccFbaBoxUp> tccFbaBoxUpList = new TccFbaBoxUp().setBidFbaPlan(bid).queryList();

				//计划单子表信息
				List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(bid).queryList();

				TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(bid).queryFirst();
				//店铺信息
				TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(tccFbaPlan.getShopId()).queryFirst();

				BigDecimal tagStateGoodsNum = BigDecimal.ZERO;
				BigDecimal tagStateTransparentNum = BigDecimal.ZERO;
				BigDecimal tagStateEurNum = BigDecimal.ZERO;
				int boxNum = 0;

				for(TccFbaBoxUp tccFbaBoxUp:tccFbaBoxUpList){
					//获取装箱单商品信息
					List<TccFbaBoxUpItem> itemList = new TccFbaBoxUpItem().setBidBoxUp(tccFbaBoxUp.getBid()).queryList();

					for(TccFbaBoxUpItem item:itemList){
						int planBoxUpNum = item.getPlanBoxUpNum();
						List<TccFbaPlanItem> tccFbaPlanItemListNew = tccFbaPlanItemList.stream()
								.filter(tccFbaPlanItem -> tccFbaPlanItem.getId().equals(item.getFbaPlanItemId()))
								.collect(Collectors.toList());
						TccFbaPlanItem tccFbaPlanItem = tccFbaPlanItemListNew.get(0);
						//商品标
						tagStateGoodsNum = tagStateGoodsNum.add(new BigDecimal(planBoxUpNum));
						//是否打印透明标
						if(tccFbaPlanItem.getIsSign().equals("是")){
							tagStateTransparentNum = tagStateTransparentNum.add(new BigDecimal(planBoxUpNum));
						}
						if(tpAmazonShop.getEuStatus() == 1){
							tagStateEurNum = tagStateEurNum.add(new BigDecimal(planBoxUpNum));
						}
					}
					boxNum = boxNum + tccFbaBoxUp.getBoxNum();//箱子数
				}
				// 整单计费 = 商品数*0.2+透明计划标商品数*0.6+欧代标商品数*0.6+箱子数*15
				unifiedAmount = tagStateGoodsNum.multiply(new BigDecimal(0.2))      // 商品数*0.2
						.add(tagStateTransparentNum.multiply(new BigDecimal(0.6)))  // +透明计划标商品数*0.6
						.add(tagStateEurNum.multiply(new BigDecimal(0.6)))          // +欧代标商品数*0.6
						.add(new BigDecimal(boxNum).multiply(new BigDecimal(15)));                  // +箱子数*15
				unifiedAmount = unifiedAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
				//计费说明
				amountExplain = "箱数："+boxNum+"；商品数："+tagStateGoodsNum+"；透明计划商品数："+tagStateTransparentNum+"；欧代标商品数："+tagStateEurNum+"；";
			}


			//装箱单取消
			else if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaBoxUp.value){
				//获取装箱单信息
				TccFbaBoxUp chooseBoxUp = new TccFbaBoxUp().setBid(bid).queryFirst();
				TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(chooseBoxUp.getBidFbaPlan()).queryFirst();
			if(chooseBoxUp==null || chooseBoxUp.getId()==null){
				return W.error(model, "单号有误");
			}
				List<TccFbaBoxUp> tccFbaBoxUpList = new TccFbaBoxUp().setBidFbaPlan(chooseBoxUp.getBidFbaPlan()).queryList();
				bidFbaPlan = chooseBoxUp.getBidFbaPlan();
				List<Map<String, Object>> itemTableDataList = new ArrayList<>();
				for(TccFbaBoxUp tccFbaBoxUp:tccFbaBoxUpList){
					int boxState = tccFbaBoxUp.getBoxState();//("未配货", 0),("已装箱", 1),("已取消", 2),("已审核", 3),("已配货", 4)
					//获取装箱单商品信息
					List<TccFbaBoxUpItem> itemList = new TccFbaBoxUpItem().setBidBoxUp(bid).queryList();

					BigDecimal tagStateGoodsNumTotal = BigDecimal.ZERO;
					BigDecimal tagStateTransparentNumTotal = BigDecimal.ZERO;
					BigDecimal tagStateEurNumTotal = BigDecimal.ZERO;

					for(TccFbaBoxUpItem item:itemList){
						int planBoxUpNum = item.getPlanBoxUpNum();
						TccFbaPlanItem tccFbaPlanItem = new TccFbaPlanItem().setId(item.getFbaPlanItemId()).queryFirst();

						if(item.getTagStateGoods().equals(TccFbaBoxUpItemEnum.TagStateGoods.YES.value) && tccFbaPlanItem.getNumPlanDeliver()>0){
							tagStateGoodsNumTotal = tagStateGoodsNumTotal.add(new BigDecimal(planBoxUpNum));
						}
						if(item.getTagStateTransparent().equals(TccFbaBoxUpItemEnum.TagStateTransparent.YES.value) && !tccFbaPlanItem.getIsSign().equals("否") && checkUtil.isNotNullByObject(tccFbaPlanItem.getAnnexFile())){
							tagStateTransparentNumTotal = tagStateTransparentNumTotal.add(new BigDecimal(planBoxUpNum));
						}
						if(item.getTagStateEur().equals(TccFbaBoxUpItemEnum.TagStateEur.YES.value)){
							TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(tccFbaPlan.getShopId()).queryFirst();
							if(!(tpAmazonShop!=null && tpAmazonShop.getEuStatus()!=null && tpAmazonShop.getEuStatus()==0)){
								tagStateEurNumTotal = tagStateEurNumTotal.add(new BigDecimal(planBoxUpNum));
							}
						}
					}

					//获取 商品标/透明标/欧代标已打印 数量
					//long tagStateGoodsNum = itemList.stream().filter(e->e.getTagStateGoods().equals(TccFbaBoxUpItemEnum.TagStateGoods.YES.value)).count();
					//long tagStateTransparentNum = itemList.stream().filter(e->e.getTagStateTransparent().equals(TccFbaBoxUpItemEnum.TagStateTransparent.YES.value)).count();
					//long tagStateEurNum = itemList.stream().filter(e->e.getTagStateEur().equals(TccFbaBoxUpItemEnum.TagStateEur.YES.value)).count();

					int boxNum = tccFbaBoxUp.getBoxNum();//箱子数

					if(boxState == TccFbaBoxUpEnum.BoxState.YES_UP.value){//已装箱
						// 整单计费 = 商品数*0.2+透明计划标商品数*0.6+欧代标商品数*0.6+箱子数*15
						unifiedAmount = tagStateGoodsNumTotal.multiply(new BigDecimal(0.2))      // 商品数*0.2
								.add(tagStateTransparentNumTotal.multiply(new BigDecimal(0.6)))  // +透明计划标商品数*0.6
								.add(tagStateEurNumTotal.multiply(new BigDecimal(0.6)))          // +欧代标商品数*0.6
								.add(new BigDecimal(boxNum).multiply(new BigDecimal(15)));                  // +箱子数*15
						//计费说明
						amountExplain = "箱数："+boxNum+"；商品数："+tagStateGoodsNumTotal+"；透明计划商品数："+tagStateTransparentNumTotal+"；欧代标商品数："+tagStateEurNumTotal+"；";

					}else if(boxState == TccFbaBoxUpEnum.BoxState.YES_DIS.value){//已配货
						// 整单计费 = 商品数*0.2+透明计划标商品数*0.6+欧代标商品数*0.6
						unifiedAmount = tagStateGoodsNumTotal.multiply(new BigDecimal(0.2))      // 商品数*0.2
								.add(tagStateTransparentNumTotal.multiply(new BigDecimal(0.6)))  // +透明计划标商品数*0.6
								.add(tagStateEurNumTotal.multiply(new BigDecimal(0.6)));         // +欧代标商品数*0.6
						//计费说明
						amountExplain = "商品数："+tagStateGoodsNumTotal+"；透明计划商品数："+tagStateTransparentNumTotal+"；欧代标商品数："+tagStateEurNumTotal+"；";
					}else if(boxState == TccFbaBoxUpEnum.BoxState.NOT_UP.value){// 未配货
						//默认原货位
						isOriginallyChw = 1;//是否原货位 0否1是
					}else {
						amountExplain = "该装箱单"+TccFbaBoxUpEnum.BoxState.getName(boxState)+"，不能操作取消";
					}

					Map<String, Object> itemTableData = new HashMap<>();
					itemTableData.put("bid",bid);//装箱单号
					itemTableData.put("boxState",boxState);//货件状态
					itemTableData.put("unifiedAmount",unifiedAmount);//整单计费
					itemTableData.put("amountExplain",amountExplain);//计费说明
					itemTableDataList.add(itemTableData);
				}
				// 子列表配置信息
				subGridConfig = commonApiService.getSubGrid(menuId_BoxUpdoCancel,itemTableDataList);
			}



			//填入返回值
			extraParam.put("isOriginallyChw",isOriginallyChw);//是否原货位 0否1是
			extraParam.put("vck",vck);//仓库
			extraParam.put("vkq",vkq);//库区
			extraParam.put("vhw",vhw);//货位
			extraParam.put("chw",chw);//货位编码
			extraParam.put("skuAmount",skuAmount);//按SKU计费标准
			extraParam.put("boxAmount",boxAmount);//按箱计费标准
			extraParam.put("unifiedAmount",unifiedAmount);//整单计费
			extraParam.put("amountExplain",amountExplain);//计费说明
			extraParam.put("bid",bid);//单号
			extraParam.put("formType",formType);//表单类型
			extraParam.put("bidFbaPlan",bidFbaPlan);//FBA计划单号
			//装箱单取消
			if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaBoxUp.value){

				commonApiService.toEdit(model,menuId_BoxUpdoCancel, new YsMenu(), menuId_BoxUpdoCancel, extraParam, subGridConfig);
			}else{
				commonApiService.toEdit(model,menuId_doCancel, new YsMenu(), menuId_doCancel, extraParam, null);
			}
			return "storage/tccFbaCancel/toEdit";
		}catch (Exception e) {
			logger.error("编辑页面出错：",e.getMessage(),e);
			return W.error(model, e.getMessage());
		}
	}



	/**
	 * 计划取消弹框 - 查询页面
	 * @param bid 对应单号
	 * @param formType 表单类型
	 */
	@GetMapping("/doCancelBySearch")
	public String doCancelBySearch(Model model, HttpServletRequest request, HttpServletResponse response, String bid,int formType) {
		try {

			//装箱单取消
			if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaBoxUp.value){
				TccFbaBoxUp tccFbaBoxUp = new TccFbaBoxUp().setBid(bid).queryFirst();
				if(!tccFbaBoxUp.getBoxState().equals(TccFbaBoxUpEnum.BoxState.YES_CANCEL.value)){
					return W.error(model, "该装箱单不是取消状态，无取消信息");
				}
				List<Map<String, Object>> itemTableDataList = new TccFbaCancel()
						.setBidFbaPlan(tccFbaBoxUp.getBidFbaPlan())
						.queryMap();
				if(itemTableDataList==null || itemTableDataList.size()<=0){
					return W.error(model, "未记录取消信息");
				}
				Map<String, Object> extraParam = itemTableDataList.get(0);
				extraParam.put("bid",bid);
				SubGridConfigDto subGridConfig = commonApiService.getSubGrid(menuId_BoxUpdoCancel,itemTableDataList);
				commonApiService.toDetail(model,menuId_BoxUpdoCancel, new YsMenu(), menuId_BoxUpdoCancel, extraParam, subGridConfig);
			}else{
				TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(bid).queryFirst();
				if(!tccFbaPlan.getStatus().equals(TccFbaPlanEnum.Status.CANCELED.value)){
					return W.error(model, "该单据不是取消状态，无取消信息");
				}

				Map<String, Object> extraParam = new TccFbaCancel()
						.setBidFbaPlan(bid)
						.queryFirstMap();
				if(extraParam==null){
					return W.error(model, "未记录取消信息");
				}
				extraParam.put("bid",bid);
				commonApiService.toDetail(model,menuId_doCancel, new YsMenu(), menuId_doCancel, extraParam, null);
			}
			return "storage/tccFbaCancel/toEdit";
		}catch (Exception e) {
			logger.error("查询页面出错：",e.getMessage(),e);
			return W.error(model, e.getMessage());
		}
	}



}






